from __future__ import absolute_import, division

from gui.panda.base import *

from ..utils import ValueField


class Placeholder(Object):
    resources = Attribute()
    parent    = Attribute()
    id        = Attribute()
    object    = Attribute()
    
    root = Attribute(initiable = False)

    def update(self):
        pass
    
    def remove(self):
        self.root.removeNode()


class PlaceholderBuilding(Placeholder):
    virtual = Attribute(initial = False)
    
    def setup(self):
        maker = CardMaker('placeholder-' + str(self.id))
        maker.setFrame(0, self.object.size, 0, self.object.size)
        
        self.root = self.parent.attachNewNode(maker.generate())
        self.root.setP(-90)
        
        self.root.setTexture(self.texture)
        
        if self.virtual:
            self.root.setTransparency(TransparencyAttrib.MAlpha)
            self.root.setAlphaScale(0.5)
        
        self.update()
    
    def update(self):
        z = 1.21

        self.root.setPos(self.object.position.x, self.object.city.map.height - self.object.position.y - self.object.size, z)
        
        self.object.clear_changed()
    
    @property
    def texture(self):
        image = PNMImage(100, 100)
        image.fill(*self.object.color.rgb)
        
        if not self.object.is_passable:
            for d in range(100):
                for e in range(6 // self.object.size):
                    f = 99 - e
                    
                    image.setXel(d, e, 0)
                    image.setXel(d, f, 0)
                    image.setXel(e, d, 0)
                    image.setXel(f, d, 0)

        texture = Texture()
        texture.load(image)
        
        return texture


class PlaceholderPerson(Placeholder):
    def setup(self):
        self.root = self.resources.load_model('Sphere')
        self.root.reparentTo(self.parent)
        self.root.setScale(0.2)
        self.update()
    
    def update(self):
        z = 1.31

        self.root.setColor(*self.object.color.rgba)
        self.root.setPos(self.object.real_x + 0.5, self.object.city.map.height - self.object.real_y - 0.5, z)


class PlaceholderTree(Placeholder):
    def setup(self):
        self.root = self.resources.load_model('Cedar')
        self.root.reparentTo(self.parent)
        self.root.setScale(0.02)
        self.root.setPos(self.object.x + 0.5, self.object.source.height - self.object.y - 0.5, 1.0)
        self.update()
    